import { type Directive } from 'vue'

// 动态获取当前元素的宽高
const map = new WeakMap()
const ob = new ResizeObserver((entries) => {
  entries.forEach((entry) => {
    // 这个函数的对应的回调函数
    const handler = map.get(entry.target)
    if (handler) {
      const box = entry.borderBoxSize[0]
      handler({
        width: box.inlineSize, // 宽
        height: box.blockSize // 高
      })
    }
  })
})

export const sizeDirect: Directive<HTMLElement, string> = {
  mounted(el, bing) {
    // 监视尺寸的变化
    ob.observe(el)
    map.set(el, bing.value)
  },
  unmounted(el) {
    ob.unobserve(el)
  }
}
